package com.journal.book.controller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.journal.common.annotation.Log;
import com.journal.common.core.controller.BaseController;
import com.journal.common.core.domain.AjaxResult;
import com.journal.common.core.domain.R;
import com.journal.common.enums.BusinessType;
import com.journal.common.utils.StringUtils;
import com.journal.common.utils.http.HttpUtils;
import com.journal.common.utils.ip.AddressUtils;
import com.journal.common.utils.ip.IpUtils;
import com.journal.book.domain.PageVisit;
import com.journal.book.service.IPageVisitService;
import com.journal.common.utils.poi.ExcelUtil;
import com.journal.common.core.page.TableDataInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 页面访问记录Controller
 *
 * @author mobin
 * @date 2025-01-XX
 */
@RestController
@RequestMapping("/book/pageVisit")
public class PageVisitController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(PageVisitController.class);

    @Autowired
    private IPageVisitService pageVisitService;

    /**
     * 记录页面访问（小程序调用）
     * 支持两种方式：POST 请求体 或 GET/POST 查询参数
     *
     * @param request HttpServletRequest 用于获取客户端IP
     * @param pagePath 页面路径
     * @param pageName 页面名称（可选）
     * @param userIdentifier 用户唯一标识（可选）
     * @param brand 手机品牌（可选）
     * @param model 设备型号（可选）
     * @param osName 操作系统名称（可选）
     * @return 结果
     */
    @PostMapping("/record")
    public R<Object> recordVisit(
        HttpServletRequest request,
        @RequestParam(value = "pagePath", required = false) String pagePath,
        @RequestParam(value = "pageName", required = false) String pageName,
        @RequestParam(value = "userIdentifier", required = false) String userIdentifier,
        @RequestParam(value = "brand", required = false) String brand,
        @RequestParam(value = "model", required = false) String model,
        @RequestParam(value = "osName", required = false) String osName)
    {
        // 如果 pagePath 为空，返回错误
        if (pagePath == null || pagePath.isEmpty()) {
            return R.fail("页面路径不能为空");
        }

        // 获取客户端IP地址和地理位置（使用公共方法）
        String[] ipInfo = getIpAndLocation(request);
        String ipAddress = ipInfo[0];
        String location = ipInfo[1];

        int result = pageVisitService.recordPageVisit(pagePath, pageName, userIdentifier, 
                                                       ipAddress, location, brand, model, osName);
        return result > 0 ? R.ok() : R.fail("记录访问失败");
    }

    /**
     * 获取客户端IP地址和地理位置（公共方法）
     * 
     * @param request HttpServletRequest
     * @return 数组，[0]为IP地址，[1]为地理位置
     */
    private String[] getIpAndLocation(HttpServletRequest request)
    {
        String ipAddress = IpUtils.getIpAddr(request);
        String location = AddressUtils.getLocationByIP(ipAddress);
        return new String[]{ipAddress, location};
    }

    /**
     * 查询页面访问记录列表
     */
    @PreAuthorize("@ss.hasPermi('book:pageVisit:list')")
    @GetMapping("/list")
    public TableDataInfo list(PageVisit pageVisit)
    {
        startPage();
        List<PageVisit> list = pageVisitService.selectPageVisitList(pageVisit);
        return getDataTable(list);
    }

    /**
     * 导出页面访问记录列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, PageVisit pageVisit)
    {
        List<PageVisit> list = pageVisitService.selectPageVisitList(pageVisit);
        ExcelUtil<PageVisit> util = new ExcelUtil<PageVisit>(PageVisit.class);
        util.exportExcel(response, list, "页面访问记录数据");
    }

    /**
     * 获取页面访问记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('book:pageVisit:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pageVisitService.selectPageVisitById(id));
    }

    /**
     * 新增页面访问记录
     */
    @PreAuthorize("@ss.hasPermi('book:pageVisit:add')")
    @Log(title = "页面访问记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PageVisit pageVisit)
    {
        return toAjax(pageVisitService.insertPageVisit(pageVisit));
    }

    /**
     * 修改页面访问记录
     */
    @PreAuthorize("@ss.hasPermi('book:pageVisit:edit')")
    @Log(title = "页面访问记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PageVisit pageVisit)
    {
        return toAjax(pageVisitService.updatePageVisit(pageVisit));
    }

    /**
     * 删除页面访问记录
     */
    @PreAuthorize("@ss.hasPermi('book:pageVisit:remove')")
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pageVisitService.deletePageVisitByIds(ids));
    }
}

